import { useAsyncEffect } from '@gnlab/utils/env-react'
import { Button, Checkbox, InputNumber } from 'antd'
import { OrderedMap } from 'immutable'
import pick from 'lodash/pick'
import ChooseGroupsToJoin from '@/desktop/components/ChooseGroupsToJoin'
import Loading from '@/desktop/components/Loading'
import services from '@/services'
import { type GroupInviteWord, emptyWords, WordType } from '@/services/common/definition'
import type { GroupContact } from '@/services/contact-types'
import './index.module.less'

const defaults = emptyWords[WordType.GroupInvite]

export default function EditGroupInvite(props: {
  word: GroupInviteWord
  wxids?: string[] // 若指定，则只列出指定企微所在的群
  onSave: (item: Required<GroupInviteWord>) => void
  onCancel: () => void
}) {
  const { word: initialWord, wxids, onSave } = props

  // 加载所有账号的群列表
  const [groupMap, setGroupMap] = useState<OrderedMap<string, GroupContact> | null>(null)
  useAsyncEffect(async () => {
    const wxidSet = wxids ? new Set(wxids) : await services.qywxs.getAllAccountWxids()
    if (wxidSet.size) {
      const groupRes = await services.groups.request({ wxids: [...wxidSet] })
      if (groupRes.success) {
        setGroupMap(OrderedMap(groupRes.data.map(group => [group.id, group])))
        return
      }
    }
    setGroupMap(OrderedMap())
  }, [wxids])

  const [choosed, setChoosed] = useState(() => initialWord.Rooms)
  const [queue, setQueue] = useState(initialWord.IsSingle ?? defaults.IsSingle)
  const [queueMemberLimit, setQueueMemberLimit] = useState(
    initialWord.MemberCount ?? defaults.MemberCount,
  )

  const formatItemAndSave = useCallback(() => {
    const item = {
      ...initialWord,
      Rooms: choosed,
      IsSingle: queue,
      MemberCount: queueMemberLimit,
      roomInfos: choosed
        .map(conversationId => {
          const group = groupMap?.find(group => group.conversationId === conversationId)
          return group ? pick(group, 'conversationId', 'name', 'isExternal') : null
        })
        .filter((v): v is Required<GroupInviteWord>['roomInfos'][number] => v !== null),
    }
    onSave(item)
  }, [initialWord, choosed, queue, queueMemberLimit, onSave, groupMap])

  const saveView = <div styleName="save">
    <div styleName="tips">
      请确保发送群邀请的企业微信账号在群内，
      <br />
      否则将无法发送群邀请
    </div>
    <Button type="primary" onClick={() => formatItemAndSave()} disabled={!choosed.length}>
      保存
    </Button>
  </div>

  const queueForm = <div styleName="queue-panel">
    <h2>邀请方式</h2>
    <div styleName={queue ? '' : 'disabled'}>
      <Checkbox checked={queue} onChange={e => setQueue(e.target.checked)}>
        按顺序邀请，当群人数超过
      </Checkbox>
      <InputNumber
        disabled={!queue}
        value={queueMemberLimit}
        onChange={value => setQueueMemberLimit(value ?? defaults.MemberCount)}
        min={0}
        controls={false}
      />
      <span>人后，邀请进入下一个群</span>
    </div>
    <div styleName="tips">
      勾选“顺序邀请”将按照选择群聊的顺序发送群邀请，一次只发送一个群邀请，达到人数上限后切换下一个群。不勾选则邀请进入全部选择的群。
    </div>
  </div>

  return <main styleName="edit-group-invite">
    {groupMap ? (
      <ChooseGroupsToJoin
        combine={true}
        sortable={true}
        groups={groupMap}
        choosed={choosed}
        setChoosed={setChoosed}
        extendPrefix={queueForm}
        extendView={saveView}
      />
    ) : (
      <Loading tip="正在加载群列表..." />
    )}
  </main>
}
